package com.example.noteshare.asyncTasks;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.example.noteshare.Utilities.HTTP;
import com.example.noteshare.Utilities.RequestType;
import com.example.noteshare.gson.MyFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

public class AsyncDownload extends AsyncTask<String, Void, String> {
	
	private String url;
	private Map<String, String> params;
	private String fileLocation;
	private Context ctx;
	
	public AsyncDownload(final String url, final Map<String, String> params, final String fileLocation, final Context ctx){
		this.url = url;
		this.params = params;
		this.fileLocation = fileLocation;
		this.ctx = ctx;
	}

	@Override
	protected String doInBackground(String... arg0) {
		//Toast.makeText(ctx, "File download started", Toast.LENGTH_LONG).show();
		return HTTP.doRequest(RequestType.GET, url, params);
	}
	
	@Override
	protected void onPostExecute(String result) {
		Gson gson = new GsonBuilder().create();
		MyFile cr = gson.fromJson(result, MyFile.class);
		
		byte[] decoded = cr.getFile().getBytes();
		File f = new File(fileLocation + cr.getName());
		
		String message = "File downloaded successfully";
		try {
			if(!f.exists()){
				FileOutputStream out = new FileOutputStream(f);
				out.write(decoded);
				out.close();
			}else{
				message = "File already exists";
			}
		} catch (FileNotFoundException e) {
			message ="File failed to download";
			e.printStackTrace();
		} catch (IOException e) {
			message = "File failed to download";
			e.printStackTrace();
		}
		Toast.makeText(ctx, message, Toast.LENGTH_LONG).show();
		
	}

}
